<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use think\captcha\Captcha;
use think\Controller;
use think\Request;
use think\facade\Request as Rq;

class Login extends Controller
{
    //加载登录的表单页面
    public function login()
    {
        return $this->fetch();
    }

    //登录验证
    public function doLogin(Request $request)
    {
        //接收表单提交的数据
        //方式一：Request对象的param()可以接收任何方式的数据（get或者post数据都能接收到）
        //$admin_name=$request->param('admin_name');
        //方式二： Request类的静态方法获取
        //$admin_name=Rq::param('admin_name');
        //方式三：辅助函数
        //$admin_name=request()->param('admin_name');
        //方式四：post()
        //$admin_name=$request->post('admin_name');
        //方式五：辅助函数input()
        //$admin_name=input('post.admin_name');

        $admin_name = input('post.admin_name','','trim');
        $admin_password = input('post.admin_password','','trim');
        $code = input('post.code');
        //1.非空验证
        if(empty($admin_name) || empty($admin_password) || empty($code)){
            return $this->error('用户名、密码、验证码不能为空','/admin/login/login');
        }
        //2.验证验证码是否正确
        $captcha = new Captcha();
        /*if (!$captcha->check($code)) {
            // 验证失败
            return $this->error('验证码失败','/admin/login/login');
        }*/

        //3.验证用户名和密码是否正确
        $resutl= (new Admin())->checkUser($admin_name,sha1($admin_password));
        if(!$resutl){
            return $this->error('用户名或者密码不正确','/admin/login/login');
        }
        //4.登录成功,保存用户登录信息
        session('admin_name',$resutl->admin_name);
        session('admin_id',$resutl->id);
        //5.跳转到后台首页
        return $this->success('登录成功','/admin/index/index');
    }

    //生成验证码
    public function verify()
    {
        $config = [
            // 验证码字体大小
            'fontSize' => 15,
            // 验证码位数
            'length' => 3,
            // 关闭验证码杂点
            'useNoise' => false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    //退出登录
    public function logout(){
          //清除session
         session(null);
         $this->success('退出成功','login');
    }
}
